#!/bin/bash
set -e

# allow specifying own .pm2.config.json to override the default. it must
# however define an `app` application, and this entry point will only start
# that one rather than all defined applications
if [ ! -e "/usr/src/app/.pm2.config.json" ]; then
  cp /usr/src/app/.pm2.config.default.json /usr/src/app/.pm2.config.json
  echo "/usr/src/app/.pm2.config.json: default config generated."
fi

# generate nginx conf from ERB
for file in /usr/src/nginx/{,**/}*.erb; do
  if [ -f "$file" ]; then
    # don't overwrite an existing destination file
    if [ ! -e "${file%.*}" ]; then
      erb -T- "$file" > "${file%.*}"
      echo "${file%.*}: generated."
    else
      >&2 echo "${file%.*}: SKIPPED! refusing to overwrite existing file."
    fi
  fi
done

# start node web service under pm2 behind nginx
exec supervisord -c /usr/src/supervisord/supervisord.conf
